import akshare as ak
import re
import logging
import pandas as pd
from typing import List, Dict
from datetime import datetime
from core import BaseDataAdapter

logger = logging.getLogger(__name__)

class AKShareStockAdapter(BaseDataAdapter):
    """A股股票数据适配器"""
    
    def __init__(self,**kwargs):
        super(AKShareStockAdapter).__init__(**kwargs)
    
    @staticmethod
    def format_symbol(symbol: str) -> str:
        return re.sub(r"\.(SH|SZ)$", "", symbol)

    @classmethod
    async def get_historical_data(cls, symbol: str, start: datetime, end: datetime) -> List[Dict]:
        formatted_symbol = cls.format_symbol(symbol)
        try:
            df = ak.stock_zh_a_hist(
                symbol=formatted_symbol,
                period="daily",
                start_date=start.strftime("%Y%m%d"),
                end_date=end.strftime("%Y%m%d"),
                adjust="qfq"
            )
            return cls.validate_data(df)
        except Exception as e:
            logger.error(f"股票数据获取失败: {str(e)}")
            return []

    @classmethod
    def validate_data(cls, df: pd.DataFrame) -> List[Dict]:
        return [{
            'date': row['日期'].strftime("%Y-%m-%d"),
            'open': round(row['开盘'], 2),
            'high': round(row['最高'], 2),
            'low': round(row['最低'], 2),
            'close': round(row['收盘'], 2),
            'volume': int(row['成交量']),
            'amount': round(row['成交额'], 2)
        } for _, row in df.iterrows()]
